<?php /* CLASSES $Id: ui.class.php,v 1.85.4.7 2007/02/11 11:27:22 cyberhorse Exp $ */
/**
 * @package dotproject
 * @subpackage core
 * @license http://opensource.org/licenses/gpl-license.php GPL License Version 2
 */

if (! defined('DP_BASE_DIR')) {
	die('This file should not be called directly');
}

// Message No Constants
define( 'UI_MSG_OK', 1 );
define( 'UI_MSG_ALERT', 2 );
define( 'UI_MSG_WARNING', 3 );
define( 'UI_MSG_ERROR', 4 );

// global variable holding the translation array
$GLOBALS['translate'] = array();

define( "UI_CASE_MASK", 0x0F );
define( "UI_CASE_UPPER", 1 );
define( "UI_CASE_LOWER", 2 );
define( "UI_CASE_UPPERFIRST", 3 );

define ("UI_OUTPUT_MASK", 0xF0);
define ("UI_OUTPUT_HTML", 0);
define ("UI_OUTPUT_JS", 0x10);
define ("UI_OUTPUT_RAW", 0x20);

// DP_BASE_DIR is set in base.php and fileviewer.php and is the base directory
// of the dotproject installation.
require_once DP_BASE_DIR."/classes/permissions.class.php";
/**
 * The Application User Interface Class.
 *
 * @author Andrew Eddie <eddieajau@users.sourceforge.net>
 * @version $Revision: 1.85.4.7 $
 */
class CAppUI {
	/** @var array generic array for holding the state of anything */
	var $state=null;
	/** @var int */
	var $user_id=null;
	/** @var string */
	var $user_first_name=null;
	/** @var string */
	var $user_last_name=null;
	/** @var string */
	var $user_company=null;
	/** @var int */
	var $user_department=null;
	/** @var string */
	var $user_email=null;
	/** @var int */
	var $user_type=null;
	/** @var array */
	var $user_prefs=null;
	/** @var int Unix time stamp */
	var $day_selected=null;

	// localisation
	/** @var string */
	var $user_locale=null;
	/** @var string */
	var $user_lang=null;
	/** @var string */
	var $base_locale = 'en'; // do not change - the base 'keys' will always be in english

	/** @var string Message string*/
	var $msg = '';
	/** @var string */
	var $msgNo = '';
	/** @var string Default page for a redirect call*/
	var $defaultRedirect = '';

	/** @var array Configuration variable array*/
	var $cfg=null;

	/** @var integer Version major */
	var $version_major = null;

	/** @var integer Version minor */
	var $version_minor = null;

	/** @var integer Version patch level */
	var $version_patch = null;

	/** @var string Version string */
	var $version_string = null;

	/** @var integer for register log ID */
	var $last_insert_id = null;

	/**
	 * CAppUI Constructor
	 */
	function CAppUI() {
		global $dPconfig;

		$this->state = array();

		$this->user_id = -1;
		$this->user_first_name = '';
		$this->user_last_name = '';
		$this->user_company = 0;
		$this->user_department = 0;
		$this->user_type = 0;

		// cfg['locale_warn'] is the only cfgVariable stored in session data (for security reasons)
		// this guarants the functionality of this->setWarning
		$this->cfg['locale_warn'] = $dPconfig['locale_warn'];

		$this->project_id = 0;

		$this->defaultRedirect = "";
		// set up the default preferences
		$this->setUserLocale($this->base_locale);
		$this->user_prefs = array();
	}

	/**
	 * Used to load a php class file from the system classes directory
	 * @param string $name The class root file name (excluding .class.php)
	 * @return string The path to the include file
	 */
	function getSystemClass( $name=null ) {
		if ($name) {
			return DP_BASE_DIR."/classes/$name.class.php";
		}
	}

	/**
	 * Used to load a php class file from the lib directory
	 *
	 * @param string $name The class root file name (excluding .class.php)
	 * @return string The path to the include file
	 */
	function getLibraryClass( $name=null ) {
		if ($name) {
			return DP_BASE_DIR."/lib/$name.php";
		}
	}

	/**
	 * Used to load a php class file from the module directory
	 * @param string $name The class root file name (excluding .class.php)
	 * @return string The path to the include file
	 */
	function getModuleClass( $name=null ) {
		if ($name) {
			return DP_BASE_DIR."/modules/$name/$name.class.php";
		}
	}

	/**
	 * Determines the version.
	 * @return String value indicating the current dotproject version
	 */
	function getVersion() {
		global $dPconfig;
		if ( ! isset($this->version_major)) {
			include_once DP_BASE_DIR . '/includes/version.php';
			$this->version_major = $dp_version_major;
			$this->version_minor = $dp_version_minor;
			$this->version_patch = $dp_version_patch;
			$this->version_string = $this->version_major . "." . $this->version_minor;
			if (isset($this->version_patch))
				$this->version_string .= "." . $this->version_patch;
			if (isset($dp_version_prepatch))
				$this->version_string .= "-" . $dp_version_prepatch;
		}
		return $this->version_string;
	}

	/**
	 * Checks that the current user preferred style is valid/exists.
	 */
	function checkStyle() {
		global $dPconfig;
		// check if default user's uistyle is installed
		$uistyle = $this->getPref("UISTYLE");

		if ($uistyle && !is_dir(DP_BASE_DIR."/style/$uistyle")) {
			// fall back to host_style if user style is not installed
			$this->setPref( 'UISTYLE', $dPconfig['host_style'] );
		}
	}

	/**
	 * Utility function to read the 'directories' under 'path'
	 *
	 * This function is used to read the modules or locales installed on the file system.
	 * @param string The path to read.
	 * @return array A named array of the directories (the key and value are identical).
	 */
	function readDirs( $path ) {
		$dirs = array();
		$d = dir( DP_BASE_DIR."/$path" );
		while (false !== ($name = $d->read())) {
			if(is_dir( DP_BASE_DIR."/$path/$name" ) && $name != "." && $name != ".." && $name != "CVS") {
				$dirs[$name] = $name;
			}
		}
		$d->close();
		return $dirs;
	}

	/**
	 * Utility function to read the 'files' under 'path'
	 * @param string The path to read.
	 * @param string A regular expression to filter by.
	 * @return array A named array of the files (the key and value are identical).
	 */
	function readFiles( $path, $filter='.' ) {
		$files = array();

		if (is_dir($path) && ($handle = opendir( $path )) ) {
			while (false !== ($file = readdir( $handle ))) {
				if ($file != "." && $file != ".." && preg_match( "/$filter/", $file )) {
					$files[$file] = $file;
				}
			}
			closedir($handle);
		}
		return $files;
	}

	/**
	 * Utility function to check whether a file name is 'safe'
	 *
	 * Prevents from access to relative directories (eg ../../dealyfile.php);
	 * @param string The file name.
	 * @return array A named array of the files (the key and value are identical).
	 */
	function checkFileName( $file ) {
		global $AppUI;

		// define bad characters and their replacement
		$bad_chars = ";/\\";
		$bad_replace = "...."; // Needs the same number of chars as $bad_chars

		// check whether the filename contained bad characters
		if ( strpos( strtr( $file, $bad_chars, $bad_replace), '.') !== false ) {
			$AppUI->setMsg('Access denied', UI_MSG_ERROR);
			$AppUI->redirect();
		}
		else {
			return $file;
		}

	}

	/**
	 * Utility function to make a file name 'safe'
	 *
	 * Strips out mallicious insertion of relative directories (eg ../../dealyfile.php);
	 * @param string The file name.
	 * @return array A named array of the files (the key and value are identical).
	 */
	function makeFileNameSafe( $file ) {
		$file = str_replace( '../', '', $file );
		$file = str_replace( '..\\', '', $file );
		return $file;
	}

	/**
	 * Sets the user locale.
	 *
	 * Looks in the user preferences first.  If this value has not been set by
	 * the user it uses the system default set in config.php.
	 *
	 * @param string Locale abbreviation corresponding to the sub-directory name
	 * in the locales directory (usually the abbreviated language code).
	 */
	function setUserLocale( $loc='', $set = true ) {
		global $dPconfig, $locale_char_set;

		$LANGUAGES = $this->loadLanguages();

		if (! $loc) {
			$loc = @$this->user_prefs['LOCALE'] ? $this->user_prefs['LOCALE'] : $dPconfig['host_locale'];
		}

		if (isset($LANGUAGES[$loc]))
			$lang = $LANGUAGES[$loc];
		else {
			// Need to try and find the language the user is using, find the first one
			// that has this as the language part
			if (strlen($loc) > 2) {
				list ($l, $c) = explode('_', $loc);
				$loc = $this->findLanguage($l, $c);
			} else {
				$loc = $this->findLanguage($loc);
			}
			$lang = $LANGUAGES[$loc];
		}
		list($base_locale, $english_string, $native_string, $default_language, $lcs) = $lang;
		if (! isset($lcs))
			$lcs = (isset($locale_char_set)) ? $locale_char_set : 'utf-8';

		if (version_compare(phpversion(), '4.3.0', 'ge'))
			$user_lang = array( $loc . '.' . $lcs, $default_language, $loc, $base_locale);
		else {
			if (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN') {
				$user_lang = $default_language;
			} else {
				$user_lang = $loc . '.' . $lcs;
			}
		}
		if ($set) {
			$this->user_locale = $base_locale;
			$this->user_lang = $user_lang;
			$locale_char_set = $lcs;
		} else {
			return $user_lang;
		}
	}

	function findLanguage($language, $country = false) {
		$LANGUAGES = $this->loadLanguages();
		$language = strtolower($language);
		if ($country) {
			$country = strtoupper($country);
			// Try constructing the code again
			$code = $language . '_' . $country;
			if (isset($LANGUAGES[$code]))
				return $code;
		}

		// Just use the country code and try and find it in the
		// languages list.
		$first_entry = null;
		foreach ($LANGUAGES as $lang => $info) {
			list($l, $c) = explode('_', $lang);
			if ($l == $language) {
				if (! $first_entry)
					$first_entry = $lang;
				if ($country && $c == $country)
					return $lang;
			}
		}
		return $first_entry;
	}

	/**
	 * Load the known language codes for loaded locales
	 *
	 */
	function loadLanguages() {

		if ( isset($_SESSION['LANGUAGES'])) {
			$LANGUAGES =& $_SESSION['LANGUAGES'];
		} else {
			$LANGUAGES = array();
			$langs = $this->readDirs('locales');
			foreach ($langs as $lang) {
				if (file_exists(DP_BASE_DIR."/locales/$lang/lang.php")) {
					include_once DP_BASE_DIR."/locales/$lang/lang.php";
				}
			}
			@$_SESSION['LANGUAGES'] =& $LANGUAGES;
		}
		return $LANGUAGES;
	}

	/**
	 * Translate string to the local language [same form as the gettext abbreviation]
	 *
	 * This is the order of precedence:
	 * <ul>
	 * <li>If the key exists in the lang array, return the value of the key
	 * <li>If no key exists and the base lang is the same as the local lang, just return the string
	 * <li>If this is not the base lang, then return string with a red star appended to show
	 * that a translation is required.
	 * </ul>
	 * @param string The string to translate
	 * @param int Option flags, can be case handling or'd with output styles
	 * @return string
	 */
	function _( $str, $flags= 0 ) {
		if (is_array($str)) {
			$translated = array();
			foreach ($str as $s)
				$translated[] = $this->__($s, $flags);
			return implode(' ', $translated);
		} else {
			return $this->__($str, $flags);
		}
	}

	function __( $str, $flags = 0) {
		global $dPconfig;
		$str = trim($str);
		if (empty( $str )) {
			return '';
		}
		$x = @$GLOBALS['translate'][$str];

		if ($x) {
			$str = $x;
		} else if (@$dPconfig['locale_warn']) {
			if ($this->base_locale != $this->user_locale ||
				($this->base_locale == $this->user_locale && !in_array( $str, @$GLOBALS['translate'] )) ) {
					$str .= @$dPconfig['locale_alert'];
				}
		}
		switch ($flags & UI_CASE_MASK) {
		case UI_CASE_UPPER:
			$str = strtoupper( $str );
			break;
		case UI_CASE_LOWER:
			$str = strtolower( $str );
			break;
		case UI_CASE_UPPERFIRST:
			$str = ucwords( $str );
			break;
		}
		/* Altered to support multiple styles of output, to fix
		 * bugs where the same output style cannot be used succesfully
		 * for both javascript and HTML output.
		 * PLEASE NOTE: The default is currently UI_OUTPUT_HTML,
		 * which is different to the previous version (which was
		 * effectively UI_OUTPUT_RAW).  If this causes problems,
		 * and they are localised, then use UI_OUTPUT_RAW in the
		 * offending call.  If they are widespread, change the
		 * default to UI_OUTPUT_RAW and use the other options
		 * where appropriate.
		 * AJD - 2004-12-10
		 */
		global $locale_char_set;

		if (! $locale_char_set) {
			$locale_char_set = 'utf-8';
		}

		switch ($flags & UI_OUTPUT_MASK) {
		case UI_OUTPUT_HTML:
			$str = htmlentities(stripslashes($str), ENT_COMPAT, $locale_char_set);
			break;
		case UI_OUTPUT_JS:
			$str = addslashes(stripslashes($str)); //, ENT_COMPAT, $locale_char_set);
			break;
		case UI_OUTPUT_RAW:
			$str = stripslashes($str);
			break;
		}
		return $str;
	}

	/**
	 * Set the display of warning for untranslated strings
	 * @param string
	 */
	function setWarning( $state=true ) {
		$temp = @$this->cfg['locale_warn'];
		$this->cfg['locale_warn'] = $state;
		return $temp;
	}

	/**
	 * Save the url query string
	 *
	 * Also saves one level of history.  This is useful for returning from a delete
	 * operation where the record more not now exist.  Returning to a view page
	 * would be a nonsense in this case.
	 * @param string If not set then the current url query string is used
	 */
	function savePlace( $query='' ) {
		if (!$query) {
			$query = @$_SERVER['QUERY_STRING'];
		}
		if ($query != @$this->state['SAVEDPLACE']) {
			$this->state['SAVEDPLACE-1'] = @$this->state['SAVEDPLACE'];
			$this->state['SAVEDPLACE'] = $query;
		}
	}

	/**
	 * Resets the internal variable
	 */
	function resetPlace() {
		$this->state['SAVEDPLACE'] = '';
	}

	/**
	 * Get the saved place (usually one that could contain an edit button)
	 * @return string
	 */
	function getPlace() {
		return @$this->state['SAVEDPLACE'];
	}

	/**
	 * Redirects the browser to a new page.
	 *
	 * Mostly used in conjunction with the savePlace method. It is generally used
	 * to prevent nasties from doing a browser refresh after a db update.  The
	 * method deliberately does not use javascript to effect the redirect.
	 *
	 * @param string The URL query string to append to the URL
	 * @param string A marker for a historic 'place, only -1 or an empty string is valid.
	 */
	function redirect( $params='', $hist='' ) {
		$session_id = SID;

		session_write_close();
		// are the params empty
		if (!$params) {
			// has a place been saved
			$params = !empty($this->state["SAVEDPLACE$hist"]) ? $this->state["SAVEDPLACE$hist"] : $this->defaultRedirect;
		}
		// Fix to handle cookieless sessions
		if ($session_id != "") {
			if (!$params)
				$params = $session_id;
			else
				$params .= "&" . $session_id;
		}
		ob_implicit_flush(); // Ensure any buffering is disabled.
		header( "Location: index.php?$params" );
		exit();	// stop the PHP execution
	}

	/**
	 * Set the page message.
	 *
	 * The page message is displayed above the title block and then again
	 * at the end of the page.
	 *
	 * IMPORTANT: Please note that append should not be used, since for some
	 * languagues atomic-wise translation doesn't work. Append should be
	 * deprecated.
	 *
	 * @param mixed The (untranslated) message
	 * @param int The type of message
	 * @param boolean If true, $msg is appended to the current string otherwise
	 * the existing message is overwritten with $msg.
	 */
	function setMsg( $msg, $msgNo=0, $append=false ) {
		$msg = $this->_( $msg, UI_OUTPUT_RAW );
		$this->msg = $append ? $this->msg.' '.$msg : $msg;
		$this->msgNo = $msgNo;
	}

	/**
	 * Display the formatted message and icon
	 * @param boolean If true the current message state is cleared.
	 */
	function getMsg( $reset=true ) {
		$img = '';
		$class = '';
		$msg = $this->msg;

		switch( $this->msgNo ) {
		case UI_MSG_OK:
			$img = createFixedSizeImage('images/info.png');
			$class = 'message';
			break;
		case UI_MSG_ALERT:
			$img = createFixedSizeImage('images/warning.png');
			$class = 'alert';
			break;
		case UI_MSG_WARNING:
			$img = createFixedSizeImage('images/warning.png');
			$class = 'warning';
			break;
		case UI_MSG_ERROR:
			$img = createFixedSizeImage('images/error.png');
			$class = 'error';
			break;
		default:
			$img = createFixedSizeImage('images/info.png');
			$class = 'message';
			break;
		}
		if ($reset) {
			$this->msg = '';
			$this->msgNo = 0;
		}
		return $msg ? '<table cellspacing="0" cellpadding="8" border="0" bgcolor="white" width="250px"><tr>'
			. '<td>'.$img.'</td>'
			. '<td class="'.$class.'" nowrap="nowrap" width="100%">'.$msg.'</td>'
			. '</tr></table>'
			: '';
	}

	function showMsg( $msg, $msgNo=0, $append=false ) {
		$this->setMsg( $msg, $msgNo, $append );
		echo $this->getMsg();
	}

	/**
	 * Set the value of a temporary state variable.
	 *
	 * The state is only held for the duration of a session.  It is not stored in the database.
	 * Also do not set the value if it is unset.
	 * @param string The label or key of the state variable
	 * @param mixed Value to assign to the label/key
	 */
	function setState( $label, $value = null) {
		if (isset($value))
			$this->state[$label] = $value;
	}

	/**
	 * Get the value of a temporary state variable.
	 * If a default value is supplied and no value is found, set the default.
	 * @return mixed
	 */
	function getState( $label, $default_value = null ) {
		if (array_key_exists( $label, $this->state)) {
			return $this->state[$label];
		} else if (isset($default_value)) {
			$this->setState($label, $default_value);
			return $default_value;
		} else  {
			return NULL;
		}
	}

	function checkPrefState($label, $value, $prefname, $default_value = null) {
		// Check if we currently have it set
		if (isset($value)) {
			$result = $value;
			$this->state[$label] = $value;
		} else if (array_key_exists($label, $this->state)) {
			$result = $this->state[$label];
		} else if (($pref = $this->getPref($prefname)) !== null) {
			$this->state[$label] = $pref;
			$result = $pref;
		} else if (isset($default_value)) {
			$this->state[$label] = $default_value;
			$result = $default_value;
		} else {
			$result = null;
		}
		return $result;
	}

	/**
	 * Login function
	 *
	 * A number of things are done in this method to prevent illegal entry:
	 * <ul>
	 * <li>The username and password are trimmed and escaped to prevent malicious
	 *     SQL being executed
	 * </ul>
	 * The schema previously used the MySQL PASSWORD function for encryption.  This
	 * Method has been deprecated in favour of PHP's MD5() function for database independance.
	 * The check_legacy_password option is no longer valid
	 *
	 * Upon a successful username and password match, several fields from the user
	 * table are loaded in this object for convenient reference.  The style, localces
	 * and preferences are also loaded at this time.
	 *
	 * @param string The user login name
	 * @param string The user password
	 * @return boolean True if successful, false if not
	 */
	function login( $username, $password ) {
		global $dPconfig;

		require_once DP_BASE_DIR."/classes/authenticator.class.php";

		$auth_method = isset($dPconfig['auth_method']) ? $dPconfig['auth_method'] : 'sql';
		if (@$_POST['login'] != 'login' && @$_POST['login'] != $this->_('login') && $_REQUEST['login'] != $auth_method)
			die("You have chosen to log in using an unsupported or disabled login method");
		$auth =& getauth($auth_method);

		$username = trim( db_escape( $username ) );
		$password = trim($password);

		if (!$auth->authenticate($username, $password)) {
			return false;
		}

		$user_id = $auth->userId($username);
		$username = $auth->username; // Some authentication schemes may collect username in various ways.
		// Now that the password has been checked, see if they are allowed to
		// access the system
		if (! isset($GLOBALS['acl']))
			$GLOBALS['acl'] =& new dPacl;
		if ( ! $GLOBALS['acl']->checkLogin($user_id)) {
			dprint(__FILE__, __LINE__, 1, "Permission check failed");
			return false;
		}

		$q  = new DBQuery;
		$q->addTable('users');
		$q->addQuery('user_id, contact_first_name as user_first_name, contact_last_name as user_last_name, contact_company as user_company, contact_department as user_department, contact_email as user_email, user_type');
		$q->addJoin('contacts', 'con', 'contact_id = user_contact');
		$q->addWhere("user_id = $user_id AND user_username = '$username'");
		$sql = $q->prepare();
		$q->clear();
		dprint(__FILE__, __LINE__, 7, "Login SQL: $sql");

		if( !db_loadObject( $sql, $this ) ) {
			dprint(__FILE__, __LINE__, 1, "Failed to load user information");
			return false;
		}

		// load the user preferences
		$this->loadPrefs( $this->user_id );
		$this->setUserLocale();
		$this->checkStyle();
		return true;
	}

	/**
	 * @Function for regiser log in dotprojet table "user_access_log"
	 */
	function registerLogin(){
		$q  = new DBQuery;
		$q->addTable('user_access_log');
		$q->addInsert('user_id', "$this->user_id");
		$q->addInsert('date_time_in', 'now()', false, true);
		$q->addInsert('user_ip', $_SERVER['REMOTE_ADDR']);
		$q->exec();
		$this->last_insert_id = db_insert_id();
		$q->clear();
	}

	/**
	 * @Function for register log out in dotproject table "user_acces_log"
	 */
	function registerLogout($user_id){
		$q  = new DBQuery;
		$q->addTable('user_access_log');
		$q->addUpdate('date_time_out', date("Y-m-d H:i:s"));
		$q->addWhere("user_id = '$user_id' and (date_time_out='0000-00-00 00:00:00' or isnull(date_time_out)) ");
		if ($user_id > 0){
			$q->exec();
			$q->clear();
		}
	}

	/**
	 * @Function for update table user_acces_log in field date_time_lost_action
	 */
	function updateLastAction($last_insert_id){
		$q  = new DBQuery;
		$q->addTable('user_access_log');
		$q->addUpdate('date_time_last_action', date("Y-m-d H:i:s"));
		$q->addWhere("user_access_log_id = $last_insert_id");
		if ($last_insert_id > 0){
			$q->exec();
			$q->clear();
		}
	}

	/**
	 * @deprecated
	 */
	function logout() {
	}

	/**
	 * Checks whether there is any user logged in.
	 */
	function doLogin() {
		return ($this->user_id < 0) ? true : false;
	}

	/**
	 * Gets the value of the specified user preference
	 * @param string Name of the preference
	 */
	function getPref( $name ) {
		return @$this->user_prefs[$name];
	}

	/**
	 * Sets the value of a user preference specified by name
	 * @param string Name of the preference
	 * @param mixed The value of the preference
	 */
	function setPref( $name, $val ) {
		$this->user_prefs[$name] = $val;
	}

	/**
	 * Loads the stored user preferences from the database into the internal
	 * preferences variable.
	 * @param int User id number
	 */
	function loadPrefs( $uid=0 ) {
		$q  = new DBQuery;
		$q->addTable('user_preferences');
		$q->addQuery('pref_name, pref_value');
		$q->addWhere("pref_user = $uid");
		$prefs = $q->loadHashList();
		$this->user_prefs = array_merge( $this->user_prefs, $prefs );
	}

	// --- Module connectors

	/**
	 * Gets a list of the installed modules
	 * @return array Named array list in the form 'module directory'=>'module name'
	 */
	function getInstalledModules() {
		$q  = new DBQuery;
		$q->addTable('modules');
		$q->addQuery('mod_directory, mod_ui_name');
		$q->addOrder('mod_directory');
		return ($q->loadHashList());
	}

	/**
	 * Gets a list of the active modules
	 * @return array Named array list in the form 'module directory'=>'module name'
	 */
	function getActiveModules() {
		$q  = new DBQuery;
		$q->addTable('modules');
		$q->addQuery('mod_directory, mod_ui_name');
		$q->addWhere('mod_active > 0');
		$q->addOrder('mod_directory');
		return ($q->loadHashList());
	}

	/**
	 * Gets a list of the modules that should appear in the menu
	 * @return array Named array list in the form
	 * ['module directory', 'module name', 'module_icon']
	 */
	function getMenuModules() {
		$q  = new DBQuery;
		$q->addTable('modules');
		$q->addQuery('mod_directory, mod_ui_name, mod_ui_icon');
		$q->addWhere("mod_active > 0 AND mod_ui_active > 0 AND mod_directory <> 'public'");
		$q->addOrder('mod_ui_order');
		return ($q->loadList());
	}

	function isActiveModule($module) {
		$q  = new DBQuery;
		$q->addTable('modules');
		$q->addQuery('mod_active');
		$q->addWhere("mod_directory = '$module'");
		$sql = $q->prepare();
		$q->clear();
		return db_loadResult($sql);
	}

	/**
	 * Returns the global dpACL class or creates it as neccessary.
	 * @return object dPacl
	 */
	function &acl() {
		if (! isset($GLOBALS['acl'])) {
			$GLOBALS['acl'] =& new dPacl;
		}
		return $GLOBALS['acl'];
	}

	/**
	 * Find and add to output the file tags required to load module-specific
	 * javascript.
	 */
	function loadJS() {
		global $m, $a, $dPconfig;
		// Search for the javascript files to load.
		if (! isset($m))
			return;
		$root = DP_BASE_DIR;
		if (substr($root, -1) != '/')
			$root .= '/';

		$base = $dPconfig['base_url'];
		if ( substr($base, -1) != '/')
			$base .= '/';
		// Load the basic javascript used by all modules.
		$jsdir = dir("{$root}js");

		$js_files = array();
		while (($entry = $jsdir->read()) !== false) {
			if (substr($entry, -3) == '.js'){
				$js_files[] = $entry;
			}
		}
		asort($js_files);
		echo '<script type="text/javascript">var SHDATEFORMAT = "'.$this->getPref('SHDATEFORMAT').'"</script>';
		while(list(,$js_file_name) = each($js_files)){
			echo "<script type=\"text/javascript\" src=\"{$base}js/$js_file_name\"></script>\n";
		}

		// additionally load overlib
		echo "<script type=\"text/javascript\" src=\"{$base}lib/overlib/overlib.js\"></script>\n";

		// load jscalendar
		$jscalendar_locale = file_exists('js/cal/lang/calendar-'.$this->user_locale.'.js') ? $this->user_locale : 'en';
		echo '<script type="text/javascript" src="js/cal/calendar.js"></script>';
		echo '<script type="text/javascript" src="js/cal/lang/calendar-'.$jscalendar_locale.'.js"></script>';
		echo '<script type="text/javascript" src="js/cal/calendar-setup.js"></script>';


		$this->getModuleJS($m, $a, true);
	}

	function getModuleJS($module, $file=null, $load_all = false) {
		global $dPconfig;
		$root = DP_BASE_DIR;
		if (substr($root, -1) != '/');
		$root .= '/';
		$base = $dPconfig['base_url'];
		if (substr($base, -1) != '/')
			$base .= '/';
		if ($load_all || ! $file) {
			if (file_exists("{$root}modules/$module/$module.module.js"))
				echo "<script type=\"text/javascript\" src=\"{$base}modules/$module/$module.module.js\"></script>\n";
		}
		if (isset($file) && file_exists("{$root}modules/$module/$file.js"))
			echo "<script type=\"text/javascript\" src=\"{$base}modules/$module/$file.js\"></script>\n";
	}

}

/**
 * Tabbed box abstract class
 */
class CTabBox_core {
	/** @var array */
	var $tabs=NULL;
	/** @var int The active tab */
	var $active=NULL;
	/** @var string The base URL query string to prefix tab links */
	var $baseHRef=NULL;
	/** @var string The base path to prefix the include file */
	var $baseInc;
	/** @var string A javascript function that accepts two arguments,
		the active tab, and the selected tab **/
	var $javascript = NULL;

	/**
	 * Constructor
	 * @param string The base URL query string to prefix tab links
	 * @param int The active tab
	 * @param string Optional javascript method to be used to execute tabs.
	 *	Must support 2 arguments, currently active tab, new tab to activate.
	 */
	function CTabBox_core( $baseHRef='', $active=0, $javascript = null ) {
		$this->tabs = array();
		$this->active = $active;
		$this->baseHRef = ($baseHRef ? "$baseHRef&" : "?");
		$this->javascript = $javascript;
		$this->baseInc = (defined('DP_CURRENT_SUBMODULE_PATH') ? DP_CURRENT_SUBMODULE_PATH : DP_CURRENT_MODULE_PATH).'/';
	}

	/**
	 * Gets the name of a tab
	 * @return string
	 */
	function getTabName( $idx ) {
		return $this->tabs[$idx][1];
	}

	/**
	 * Adds a tab to the object
	 * @param string File to include
	 * @param The display title/name of the tab
	 */
	function add( $file, $title, $from = '', $key= NULL ) {
		$t = array( 'file' => $file, 'title' => $title, 'from' => $from );
		if (isset($key))
			$this->tabs[$key] = $t;
		else
			$this->tabs[] = $t;
	}

	function isTabbed() {
		global $AppUI;
		if ($this->active < 0 || @$AppUI->getPref( 'TABVIEW' ) == 2 )
			return false;
		return true;
	}

	/* extra info */
	var $info = NULL;

	function setInfo ($info) {
		$this->info =
			'<table class="infopanel" width="100%" border="0" cellspacing="0" cellpadding="3">'.
				'<tr><td><div>'.$info.'</div></td></tr>'.
			'</table>';
	}
	/**
	 * Displays the tabbed box
	 *
	 * This function may be overridden
	 *
	 * @param string Can't remember whether this was useful
	 */
	function show( $extra='', $js_tabs = false ) {
		global $AppUI, $currentTabId, $currentTabName;
		reset( $this->tabs );
		$s = '';

		echo '<div width="100%"><img src="images/shim.gif" height="8" width="100%"></div>';
		$s = '<table width="100%" border="0" cellpadding="0" cellspacing="0"><tr>';
		if ( count($this->tabs)-1 < $this->active ) {
			//Last selected tab is not available in this view. eg. Child tasks
			$this->active = 0;
		}
		foreach( $this->tabs as $k => $v ) {
			$class = ($k == $this->active) ? 'tabon' : 'taboff';
			$action = $this->javascript ? $this->javascript . "({$this->active}, $k)" :
						($js_tabs ? 'show_tab(' . $k . ')' : "go('{$this->baseHRef}tab=$k')");
			$s .= '<td id="toptab_' . $k . '" width="1%" class="'.$class.'" onclick="'.$action.'">';
			$s .= $AppUI->_($v['title']).'</td>';
			$s .= '<td class="tabsp">&nbsp;</td>';
		}
		$s .= '<td class="tabox">&nbsp;</td></tr></table>';

		if ($this->info) {
			$s .= $this->info;
		}
		echo $s;

		$v = $this->tabs[$this->active];
		if ( $this->baseInc.$v['file'] != "" ) {
			$currentTabId = $this->active;
			$currentTabName = $v['title'];
			if (!$js_tabs) require $this->getTabFile($v);
		}

		if ($js_tabs) {
			echo '<table class="infopanel" width="100%" border="0" cellspacing="0" cellpadding="3">';
			echo '<tr><td>';
			foreach( $this->tabs as $k => $v ) {
				$s = $k != $this->active ? 'style="display: none"' : '';
				echo '<div class="tab" id="tab_'.$k.'" '.$s.'>';
				require $this->getTabFile($v);
				echo '</div>';
			}
			echo '</td></tr></table>';
		}
	}

	function getTabFile($v) {
		return ($v['from'] != '' ? DP_MODULE_PATH.'/'.$v['from'].'/' : $this->baseInc).$v['file'].'.php';
	}

	function loadExtras($module, $file = null) {
		global $AppUI;
		if (! isset($_SESSION['all_tabs']) || ! isset($_SESSION['all_tabs'][$module]))
			return false;

		if ($file) {
			if (isset($_SESSION['all_tabs'][$module][$file]) && is_array($_SESSION['all_tabs'][$module][$file])) {
				$tab_array =& $_SESSION['all_tabs'][$module][$file];
			} else {
				return false;
			}
		} else {
			$tab_array =& $_SESSION['all_tabs'][$module];
		}
		$tab_count = 0;
		foreach ($tab_array as $tab_elem) {
			if (isset($tab_elem['module']) && $AppUI->isActiveModule($tab_elem['module'])) {
				$tab_count++;
				$this->add(basename($tab_elem['file']), $tab_elem['name'], $tab_elem['module']);
			}
		}
		return $tab_count;
	}

	function findTabModule($tab) {
		global $AppUI, $m, $a;

		if (! isset($_SESSION['all_tabs']) || ! isset($_SESSION['all_tabs'][$m]))
			return false;

		if (isset($a)) {
			if (isset($_SESSION['all_tabs'][$m][$a]) && is_array($_SESSION['all_tabs'][$m][$a]))
				$tab_array =& $_SESSION['all_tabs'][$m][$a];
			else
				$tab_array =& $_SESSION['all_tabs'][$m];
		} else {
			$tab_array =& $_SESSION['all_tabs'][$m];
		}

		list($file, $name) = $this->tabs[$tab];
		foreach ($tab_array as $tab_elem) {
			if (isset($tab_elem['name']) && $tab_elem['name'] == $name && $tab_elem['file'] == $file)
				return $tab_elem['module'];
		}
		return false;
	}
}

/**
 * Title box abstract class
 */
class CTitleBlock_core {
	/** @var string The main title of the page */
	var $title='';
	/** @var string The name of the icon used to the left of the title */
	var $icon='';
	/** @var array An array of the table 'cells' to the right of the title block and for bread-crumbs */
	var $cells=null;

	/**
	 * The constructor
	 *
	 * Assigns the title, icon, module and help reference.  If the user does not
	 * have permission to view the help module, then the context help icon is
	 * not displayed.
	 */
	function CTitleBlock_core( $title, $icon='' ) {
		$this->title = $title;
		$this->icon = $icon;
		$this->cells = array();
	}

	/**
	 * Adds a table 'cell' beside the Title string
	 *
	 * Cells are added from left to right.
	 */
	function addCell( $data='', $attribs='', $prefix='', $suffix='' ) {
		$this->cells[] = array( $attribs, $data, $prefix, $suffix );
	}

	/**
	 * Add a button control to Title Block
	 */
	function addButton($name, $action, $target='', $target_opts='') {
		$this->addCell(createButton($name, $action, $target='', $target_opts=''));
	}

	/**
	 * The drawing function
	 */
	function show() {
		global $AppUI;
		$s = '<table width="100%" border="0" cellpadding="1" cellspacing="1">';
		$s .= '<tr>';
		if ($this->icon) {
			$s .= '<td width="42">';
			$s .= dPshowImage(dPFindImage( $this->icon, DP_CURRENT_MODULE ));
			$s .= '</td>';
		}
		else {
			$icon = defined('DP_CURRENT_MODULE_ICON') ? DP_CURRENT_MODULE_ICON : DP_CURRENT_MODULE.'.png';
			$s .= '<td width="42">';
			$s .= '<img src="modules/'.DP_CURRENT_MODULE.'/images/'.$icon.'">';
			$s .= '</td>';
		}
		$s .= '<td align="left" width="100%" nowrap="nowrap"><h1>' . $AppUI->_($this->title) . '</h1></td>';
		foreach ($this->cells as $c) {
			$s .= $c[2] ? $c[2] : '';
			$s .= '<td align="right" nowrap="nowrap"' . ($c[0] ? " $c[0]" : '') . '>';
			$s .= $c[1] ? $c[1] : '&nbsp;';
			$s .= '</td>';
			$s .= $c[3] ? $c[3] : '';
		}
		$s .= '</tr>';
		$s .= '</table><br/>';

		echo $s;
	}
}
// Utility functions

/**
 * Create HTML src link with image
 */
function createLinkImage($link, $image, $text, $title='') {
	$html = '<a href="'.$link.'" title="'.$title.'">' .
				'<table border="0" cellspacing="0" cellpadding="0">' .
					'<tr>' .
						'<td class="internal"><img border="0" src="'.$image.'"/></td>' .
						'<td class="internal" style="padding-left: 2px">'.$text.'</td>' .
					'</tr>' .
				'</table>' .
			'</a>';
	return $html;
}

/**
 * Display HTML link with image
 */
function showLinkImage($link, $image, $text, $title='') {
	echo createLinkImage($link, $image, $text, $title);
}

/**
 * Create HTML clickable image
 */
function createIconLink($image, $link, $title='', $extra='') {
	if (strpos($link,'js:') === 0)
		$html = '<img src="'.$image.'" class="link" title="'.$title.'" onclick="'.substr($link,3).'" '.$extra.'/>';
	else
		$html = '<img src="'.$image.'" class="link" title="'.$title.'" onclick="go(\''.$link.'\')" '.$extra.'/>';
	return $html;
}

/**
 * Display HTML clickable image
 */
function showIconLink($image, $link, $title='', $extra='') {
	echo createIconLink($image, $link, $title, $extra);
}

/**
 * Create HTML button with javascript action
 */
function createButton($name, $action, $target='', $target_opts='') {
	$action = $target != '' ? "window.open('$action', '$target', '$target_opts')" :
		(strpos($action, 'js:') === 0 ? substr($action,3) : "go('$action')");
	$html = '<input type="button" class="button" value="'.$name.'" onclick="'.$action.'"/>';
	return $html;
}

/**
 * Display HTML button with javascript action
 */
function showButton($name, $action, $target='', $target_opts='') {
	echo createButton($name, $action, $target, $target_opts);
}

/**
 * Display an empty table row with specified number of columns
 */
function showEmptyRow($col = 1, $class = '') {
	$r = $class != '' ? '<tr class="'.$class.'">' : '<tr>';
	$r .= '<td>&nbsp;</td>';
	for ($c = 1; $c < $col; $c++) $r .= '<td>&nbsp;</td>';
	$r .= '</tr>';
	echo $r;
}

/**
 * Display an empty span table row
 */
function showEmptySpanRow($class = '') {
	echo ($class != '' ? '<tr class="'.$class.'">' : '<tr>') . '<td colspan="100%">&nbsp;</td></tr>';
}

/**
 * Create a spin editor box
 */
function createSpinBox($name, $value, $minval, $maxval, $unit='', $step = 1, $disabled = false, $size = 20) {
	$id = 'id'.ucfirst($name);
	$disabled = $disabled ? 'disabled="true"' : '';

	$html = '<table class="spinner" border="0" cellpadding="0" cellspacing="1">'.
			'<tr>'.
				'<td rowspan="2" class="internal">' .
					'<input class="spin" id="'.$id.'" type="text" name="'.$name.'" value="'.$value.'" readonly="true"' .
							' min="'.$minval.'" max="'.$maxval.'" step="'.$step.'" style="width: '.$size.'px" ' .
							$disabled.'>' .
				'</td>'.
				'<td class="internal">' .
					'<img class="clickable" src="images/up.gif" ' .
						'onmousedown="Spinner(\''.$id.'\', this, 1).start()"/>' .
				'</td>'.
			'</tr>'.
			'<tr>'.
				'<td class="internal">' .
					'<img class="clickable" src="images/dn.gif" ' .
						'onmousedown="Spinner(\''.$id.'\', this, -1).start()"/>' .
				'</td>'.
			'</tr>'.
		 '</table>';
	if ($unit != '') {
		$html = '<table cellspacing="0" cellpadding="0" border="0"><tr><td>'.$html.'</td>' .
				'<td style="padding-left: 2px">'.$unit.'</td></tr></table>';
	}
	return $html;
}

/**
 * Display spin editor box
 */
function showSpinBox($name, $value, $minval, $maxval, $unit='', $step = 1, $disabled = false, $size = 20) {
	echo createSpinBox($name, $value, $minval, $maxval, $unit, $step, $disabled, $size);
}

function createFixedSizeImage($image, $w=null, $h=null) {
	if (file_exists($image) && function_exists('getimagesize'))
		$size = getimagesize($image);

	return '<img src="'.$image.'"'.
			(is_array($size) ?
				$size[3] : ($w != null ? ' width="'.$w.'"' : '') . ($h != null ? ' height="'.$h.'"' : '')
			).'/>';
}

function showFixedSizeImage($image, $w=null, $h=null) {
	echo createFixedSizeImage($image, $w, $h);
}

// !! Ensure there is no white space after this close php tag.
?>
